package com.sgb.kjwl.viewmodel.self.logistics;

import android.app.Application;
import android.text.TextUtils;
import android.view.Gravity;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.DriveStep;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.sgb.alimaplibrary.MarkerEntity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.self.OrderQuoteEntity;
import com.sgb.kjwl.model.entity.transport.OfferGoodsSourcePlaceEntity;
import com.sgb.kjwl.model.entity.transport.OwnerGoodsDetailInfo;
import com.sgb.kjwl.model.entity.transport.common.AddressItem;
import com.sgb.kjwl.model.response.ListResponse2;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.ui.activity.self.logistics.OfferThirdActivity;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.MToast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Describe:
 * Author:  yangLei
 * Date:    2021/9/17
 */
public class OfferThirdModel extends AndroidViewModel implements RouteSearch.OnRouteSearchListener {
    private int page = 1;

    private AMap aMap;
    private RouteSearch mRouteSearch;
    //装卸情况
    private String handleTypeNo;
    //装卸点经纬度信息
    private List<LatLonPoint> sourcePoints = new ArrayList<>();
    //货源信息标记集合
    private List<MarkerOptions> sourceMarkers = new ArrayList<>();
    //车主标记集合
    private List<OrderQuoteEntity> entityList = new ArrayList<>();
    private List<OrderQuoteEntity> validBeans = new ArrayList<>();
    public MutableLiveData<OwnerGoodsDetailInfo> detailsLiveData = new MutableLiveData<>();

    public OfferThirdModel(@NonNull Application application) {
        super(application);
    }

    public MutableLiveData<Integer> ldCurrOffer = new MutableLiveData<>();
    private List<AddressItem> offerPointList = new ArrayList<>();//报价方点集合
    private List<AddressItem> bundles = new ArrayList<>();
    private List<Marker> markers = new ArrayList<>();
    private Marker markerLast;
    private int lastPosition;

    public List<OrderQuoteEntity> getValidBeans() {
        return validBeans;
    }

    public void setValidBeans(List<OrderQuoteEntity> validBeans) {
        this.validBeans = validBeans;
    }

    public void setAMap(AMap aMap) {
        this.aMap = aMap;
        //添加marker点击监听
        aMap.setOnMarkerClickListener(marker -> {
            if (marker.getObject() != null) {
                AddressItem item = (AddressItem) marker.getObject();
                if (item.getPosition() >= 0) {
                    for (int i = 0; i < bundles.size(); i++) {
                        if (item.getPosition() == i) {
                            if (bundles.get(i).isBigMarkView()) {
                                setMarkStyle(i, marker, false);
                            } else {
                                setMarkStyle(i, marker, true);
                                ldCurrOffer.postValue(i);
                            }
                            if (lastPosition != i) {
                                resetMarker(false);
                            }
                            markerLast = marker;
                            lastPosition = i;
                            break;
                        }
                    }
                }
            }
            return false;
        });
    }

    /**
     * 请求最新的车主报价列表信息
     *
     * @param isMore
     * @param detailInfo 货源详情
     */
    public void getOfferOwnerList(OfferThirdActivity activity, boolean isMore, OwnerGoodsDetailInfo detailInfo) {
        if (detailInfo == null)
            return;
        page = isMore ? page + 1 : 1;
        Map map = new HashMap();
        map.put("limit", 10);
        map.put("page", page);
        map.put("goodsSourceNo", detailInfo.getNo());
        map.put("terminal", detailInfo.getTerminal());
        map.put("userNo", detailInfo.getUserNo());
        //根据当前的身份进行传参:1公司 2团队 3个人
        if (UserOperating.getInstance().isCompany()) {
            map.put("companyNo", UserOperating.getInstance().getTeamOrCompanyNameNo());
        } else if (UserOperating.getInstance().isTeam()) {
            map.put("teamNo", UserOperating.getInstance().getTeamOrCompanyNameNo());
        } else if (UserOperating.getInstance().isPersonal()) {
            //个人不用传
        }
        DialogHelper.showProgressDialog(activity, null, "加载中", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getLogisticsAPI().getOfferOwnerThirdList(map).enqueue(new Callback<BaseEntity<ListResponse2<List<OrderQuoteEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ListResponse2<List<OrderQuoteEntity>>>> call, Response<BaseEntity<ListResponse2<List<OrderQuoteEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() != null && response.body().getState().equals("ok")) {
                    if (!isMore) {
                        entityList.clear();
                    }
                    if (response.body().getData() != null && response.body().getData().getList() != null && response.body().getData().getList().size() > 0) {
                        entityList.addAll(response.body().getData().getList());
                        setOwnerMarkers(entityList);
                        activity.showOfferOwner(response.body().getData().getList(), response.body().getData().getTotal(), isMore);
                    } else {
                        setOwnerMarkers(entityList);
                        activity.showOfferOwner(null, 0, isMore);
                    }
                } else {
                    activity.showOfferOwner(null, 0, isMore);
                    if (response.body() != null)
                        MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ListResponse2<List<OrderQuoteEntity>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    /**
     * 货源详情
     */
    public void getOwnerGoodsDetailInfo(OfferThirdActivity activity, String sourceNo) {
        String isLogin = UserOperating.getInstance().isLogged() ? "true" : "false";
        NewAPIManager.getInstance().getLogisticsAPI().getManagerSourceDetail(isLogin, sourceNo).enqueue(new Callback<BaseEntity<OwnerGoodsDetailInfo>>() {
            @Override
            public void onResponse(Call<BaseEntity<OwnerGoodsDetailInfo>> call, Response<BaseEntity<OwnerGoodsDetailInfo>> response) {
                if (response.body() == null) return;
                if (response.body().getState().equals("ok")) {
                    setRouteInfo(response.body().getData());
                    detailsLiveData.postValue(response.body().getData());
                } else if ("201".equals(response.body().getCode()) && response.body().getState().equals("fail")) {
                    MToast.showToast(activity, "货源已被删除或下架");
                } else if (response.body().getState().equals("fail")) {
                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<OwnerGoodsDetailInfo>> call, Throwable t) {
                MToast.showToast(activity, "获取失败");
            }
        });
    }

    /**
     * 同意车主报价
     *
     * @param activity
     * @param id       goodsOffer报价编号
     * @param no       货源编号
     */
    public void agreeOffer(OfferThirdActivity activity, String id, String no) {
        Map map = new HashMap();
        map.put("no", id);
        map.put("goodsSourceNo", no);
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getLogisticsAPI().shipperAgreeOffer(map).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null || response.body().getCode() == null) {
                    return;
                }
                //报价成功
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.agreeOfferRefresh();
                }
                //车辆状态异常
                else if (response.body().getState().equals(APIManager.RESPONSE_FAIL)
                        && response.body().getCode().equals(APIManager.CAR_ABNORMAL)) {
                    if (!TextUtils.isEmpty(response.body().getMsg())) {
                        new RoundDialog.Builder(activity)
                                .title("车辆状态异常")
                                .content(response.body().getMsg())
                                .confirm("确定")
                                .singleBtn(true)
                                .contentGravity(Gravity.CENTER)
                                .cancelable(false)
                                .show();
                    }
                } else {
                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    /**
     * 设置路径信息
     */
    private void setRouteInfo(OwnerGoodsDetailInfo sourceDetail) {
        //装载 装卸地经纬度
        if (sourceDetail != null && !TextUtils.isEmpty(sourceDetail.getHandleTypeNo()) && sourceDetail.getPlace() != null) {
            handleTypeNo = sourceDetail.getHandleTypeNo();

            OfferGoodsSourcePlaceEntity place = sourceDetail.getPlace();
            LatLonPoint sendPoint = null;
            LatLng sendLL = null;
            if (!TextUtils.isEmpty(place.getLatitude()) && !TextUtils.isEmpty(place.getLongitude())) {
                sendPoint = new LatLonPoint(Double.parseDouble(place.getLatitude()), Double.parseDouble(place.getLongitude()));
                sendLL = new LatLng(Double.parseDouble(place.getLatitude()), Double.parseDouble(place.getLongitude()));
            }

            LatLonPoint viaSendPoint = null;
            LatLng viaSendLL = null;
            if (!TextUtils.isEmpty(place.getViaSendLatitude()) && !TextUtils.isEmpty(place.getViaSendLongitude())) {
                viaSendPoint = new LatLonPoint(Double.parseDouble(place.getViaSendLatitude()), Double.parseDouble(place.getViaSendLongitude()));
                viaSendLL = new LatLng(Double.parseDouble(place.getViaSendLatitude()), Double.parseDouble(place.getViaSendLongitude()));
            }
            LatLonPoint viaDestPoint = null;
            LatLng viaDestLL = null;
            if (!TextUtils.isEmpty(place.getViaDestLatitude()) && !TextUtils.isEmpty(place.getViaDestLongitude())) {
                viaDestPoint = new LatLonPoint(Double.parseDouble(place.getViaDestLatitude()), Double.parseDouble(place.getViaDestLongitude()));
                viaDestLL = new LatLng(Double.parseDouble(place.getViaDestLatitude()), Double.parseDouble(place.getViaDestLongitude()));
            }

            LatLonPoint destPoint = null;
            LatLng destLL = null;
            if (!TextUtils.isEmpty(place.getDestLatitude()) && !TextUtils.isEmpty(place.getDestLongitude())) {
                destPoint = new LatLonPoint(Double.parseDouble(place.getDestLatitude()), Double.parseDouble(place.getDestLongitude()));
                destLL = new LatLng(Double.parseDouble(place.getDestLatitude()), Double.parseDouble(place.getDestLongitude()));
            }
            sourceMarkers.clear();
            sourcePoints.clear();
            switch (handleTypeNo) {
                case "11":
                    sourcePoints.add(sendPoint);
                    sourcePoints.add(destPoint);
                    sourceMarkers.add(new MarkerOptions().position(sendLL).icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_samll_handle)));
                    sourceMarkers.add(new MarkerOptions().position(destLL).icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_unload)));
                    break;
                case "21":
                    sourcePoints.add(sendPoint);
                    sourcePoints.add(viaSendPoint);
                    sourcePoints.add(destPoint);
                    sourceMarkers.add(new MarkerOptions().position(sendLL).icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_loading_1)));
                    sourceMarkers.add(new MarkerOptions().position(viaSendLL).icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_loading_2)));
                    sourceMarkers.add(new MarkerOptions().position(destLL).icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_unload)));
                    break;
                case "12":
                    sourcePoints.add(sendPoint);
                    sourcePoints.add(viaDestPoint);
                    sourcePoints.add(destPoint);
                    sourceMarkers.add(new MarkerOptions().position(sendLL).icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_samll_handle)));
                    sourceMarkers.add(new MarkerOptions().position(viaDestLL).icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_unloading_1)));
                    sourceMarkers.add(new MarkerOptions().position(destLL).icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_unloading_2)));
                    break;
                case "22":
                    sourcePoints.add(sendPoint);
                    sourcePoints.add(viaSendPoint);
                    sourcePoints.add(viaDestPoint);
                    sourcePoints.add(destPoint);
                    sourceMarkers.add(new MarkerOptions().position(sendLL).icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_loading_1)));
                    sourceMarkers.add(new MarkerOptions().position(viaSendLL).icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_loading_2)));
                    sourceMarkers.add(new MarkerOptions().position(viaDestLL).icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_unloading_1)));
                    sourceMarkers.add(new MarkerOptions().position(destLL).icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_unloading_2)));
                    break;
            }
        }
    }

    /**
     * 添加需要规划的路线数据
     *
     * @param activity
     * @param points   路线连接点
     */
    public void planningLoadingRoute(OfferThirdActivity activity, List<LatLonPoint> points) {
        //路线点不能少于两个
        if (points == null || points.size() < 2) {
            return;
        }
        List<LatLonPoint> passedByPoints = null;
        //设置开始位置坐标点(注意经纬度不能写反,会报错1800(只能规划到中国区域里的地图路线))
        LatLonPoint startPoint = points.get(0);
        //设置目的地坐标点
        LatLonPoint endPoint = points.get(points.size() - 1);
        //查询信息对象
        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(startPoint, endPoint);

        if (points.size() > 2) {
            passedByPoints = new ArrayList<>();
            for (int i = 1; i < points.size() - 1; i++) {
                passedByPoints.add(points.get(i));
            }
        }
        // 对象进行初始化
        if (mRouteSearch == null)
            mRouteSearch = new RouteSearch(activity);
        // 搜索监听
        mRouteSearch.setRouteSearchListener(this);

        //设置搜索参数 1.fromAndTo 路径的起点终点  2.路径规划的策略（可选），默认为“躲避拥堵” 3.途经点，可选 4.避让区域，可选， 5.货车大小 ,默认轻型车
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(
                fromAndTo,
                RouteSearch.DRIVING_SINGLE_SHORTEST,
                passedByPoints,
                null, "");

        //开始异步查询
        mRouteSearch.calculateDriveRouteAsyn(query);
    }

    /**
     * 设置报价车主 Marker 信息
     *
     * @param entity2s
     */
    private void setOwnerMarkers(List<OrderQuoteEntity> entity2s) {
        offerPointList.clear();
        validBeans.clear();
        if (entity2s.size() <= 0)
            return;
        for (OrderQuoteEntity entity2 : entity2s) {
            if (entity2.getLatitude() != null && entity2.getLatitude() > 0 && entity2.getLongitude() != null && entity2.getLongitude() > 0) {
                if (detailsLiveData.getValue() != null) {
                    validBeans.add(entity2);
                    int imageId;
                    if (detailsLiveData.getValue().getFreightType().equals("1")) { //电议
                        imageId = R.mipmap.icon_marker_offer_personal_red;
                    } else {//一口价
                        if (!TextUtils.isEmpty(entity2.getOfferStatus()) && entity2.getOfferStatus().equals("2")) {
                            imageId = R.mipmap.icon_marker_offer_personal_yellow;
                        } else if (!TextUtils.isEmpty(entity2.getSourceAllFreight()) && !TextUtils.isEmpty(entity2.getAllFreight())) {
                            imageId = Double.parseDouble(entity2.getAllFreight()) > Double.parseDouble(entity2.getSourceAllFreight())
                                    ? R.mipmap.icon_marker_offer_personal_red : R.mipmap.icon_marker_offer_personal_green;
                        } else {
                            imageId = R.mipmap.icon_marker_offer_personal_red;
                        }
                    }
                    offerPointList.add(new AddressItem("", "", "", imageId, entity2.getLatitude(), entity2.getLongitude(), imageId, imageId));
                }
            }
        }

    }

    /**
     * 在地图上添加所有的标记
     *
     * @param activity
     * @param type     0——货源相关，1——货源和报价单位
     */
    public void addAllMarkers(OfferThirdActivity activity, int type) {
        if (aMap == null)
            return;

        //先清除一下地图控件,避免重复显示 Marker
        aMap.clear();

        //报价单位相关marker
        if (type == 1) {
            markers.clear();
            bundles.clear();
            for (int i = 0; i < offerPointList.size(); i++) {
                AddressItem entity = offerPointList.get(i);
                entity.setPosition(i);
                bundles.add(entity);
                LatLng latLng = new LatLng(entity.getLatitude(), entity.getLongitude());
                MarkerEntity markerEntity = new MarkerEntity(latLng, entity.getMakerIcon());
                Marker marker = aMap.addMarker(getMarkerOptions(markerEntity));
                marker.setObject(entity);
                markers.add(marker);
            }
        }

        //货源相关marker
        if (sourceMarkers.size() > 0) {
            for (MarkerOptions sourceMarker : sourceMarkers) {
                aMap.addMarker(sourceMarker);
            }
        }
        planningLoadingRoute(activity, sourcePoints);
    }

    public MarkerOptions getMarkerOptions(MarkerEntity markerEntity) {
        BitmapDescriptor bitmapSmall;
        if (markerEntity.getIcon() == 0 && markerEntity.getView() != null) {
            bitmapSmall = BitmapDescriptorFactory.fromView(markerEntity.getView());
        } else {
            bitmapSmall = BitmapDescriptorFactory.fromResource(markerEntity.getIcon());
        }
        MarkerOptions markerOption = new MarkerOptions()
                .position(markerEntity.getLatLng())
                .title(markerEntity.getTitle())
                .icon(bitmapSmall)
                .draggable(false);
        return markerOption;
    }

    public void resetMarkersSmall() {
        if (markers != null && markers.size() > 0) {
            for (int i = 0; i < markers.size(); i++) {
                setMarkStyle(i, markers.get(i), false);
            }
        }
    }

    // 设置maker大小图标
    private void setMarkStyle(int pos, Marker marker, boolean isBigMarkView) {
        AddressItem entity = bundles.get(pos);
        BitmapDescriptor bitmapSmall = isBigMarkView ? BitmapDescriptorFactory.fromResource(entity.getBigMakerIcon()) : BitmapDescriptorFactory.fromResource(entity.getMakerIcon());
        entity.setBigMarkView(isBigMarkView);
        marker.setIcon(bitmapSmall);
    }

    public void resetMarker(boolean close) {
        if (markerLast == null)
            return;
        AddressItem entity = bundles.get(lastPosition);
        markerLast.setIcon(BitmapDescriptorFactory.fromResource(entity.getMakerIcon()));
        entity.setBigMarkView(false);
        if (close) {
            markerLast = null;
        }
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int code) {
        if (code == 1000 && result != null && result.getPaths() != null && result.getPaths().size() > 0) {//获取规划路线成功,获取到的是了,路线坐标点的集合
            if (aMap == null)
                return;
            List<DrivePath> paths = result.getPaths();
            //创建存储坐标点的集合
            List<LatLng> latLngs = new ArrayList<>();
            //遍历获取规划的所有路线坐标点
            for (DriveStep mDriveStep : paths.get(0).getSteps()) {
                for (LatLonPoint mLatLonPoint : mDriveStep.getPolyline()) {
                    latLngs.add(new LatLng(mLatLonPoint.getLatitude(), mLatLonPoint.getLongitude()));
                }
            }

            //绘制规划路径路线
            aMap.addPolyline(new PolylineOptions()
                    //路线坐标点的集合
                    .addAll(latLngs)
                    //线的宽度
                    .width(20)
                    //设置纹理样式
                    .setCustomTexture(BitmapDescriptorFactory.fromResource(R.drawable.map_alr))
            );
            //显示完整地图路线
            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            for (int i = 0; i < latLngs.size(); i++) {
                builder.include(latLngs.get(i));
            }
            //显示全部路径点,第二个参数是四周留空宽度
            aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 200));
        }
    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }
}
